package com.zezheng.extract.project.anxinsign.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zezheng.extract.project.anxinsign.dto.response.HeaderDTO;
import com.zezheng.extract.project.anxinsign.dto.response.ResponseDTO;
import com.zezheng.extract.project.anxinsign.service.AnxinService;
import okhttp3.*;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class AnxinServiceImpl implements AnxinService, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public <R, T> void doRequest(Object requestData, Class<T> clazz, DeferredResult<R> deferredResult) {
        try {
            String url = "https://IP:Port/FEP/platId/{platId}/txCode/{txCode}/transaction";

            OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
            Request request = new Request.Builder().url(url).get().build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println("Fail");
                    dealResponseFailure(0, "" , deferredResult);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    System.out.println(response.body().string());
                    try {
                        HeaderDTO headerDTO;
                        JSONObject root = JSONObject.parseObject(response.body().string());
                        JSONArray data = root.getJSONArray("data");

                        if (data != null && data.size() > 0) {
                            root = data.getJSONObject(0);
                        }
                        T result = root.toJavaObject(clazz);
                        headerDTO = root.toJavaObject(HeaderDTO.class);
                        deferredResult.setResult((R) ResponseDTO.success(headerDTO, result, data, requestData, url));
                    } catch (Exception e) {
                        returnErrorResult(deferredResult, "-1" , "" , "-1" , "处理响应报文异常");
                    }
                }
            });
        } catch (Exception e) {
            returnErrorResult(deferredResult, "-1" , "" , "-1" , "请求异常");
        }
    }

    private <R> void dealResponseFailure(int code, String responseBody, DeferredResult<R> deferredResult) {
        String msg = "响应报文异常";
        if (code == 404) {
            msg = "功能号尚未开通";
        } else if (code == 401) {
            msg = "OAuth 认证失败";
        }

        try {
            JSONObject root = JSONObject.parseObject(responseBody);
            HeaderDTO headerDTO = root.toJavaObject(HeaderDTO.class);
            deferredResult.setResult((R) ResponseDTO.success(headerDTO, null));
        } catch (Exception e) {
            returnErrorResult(deferredResult, "1" , msg, String.valueOf(code), msg);
        }
    }

    private <R> void returnErrorResult(DeferredResult<R> deferredResult, String retCode, String retMessage, String errorCode, String errorMessage) {
        HeaderDTO headerDTO = new HeaderDTO();
        headerDTO.setRetCode(retCode);
        headerDTO.setRetMessage(retMessage);
        headerDTO.setErrorCode(errorCode);
        headerDTO.setErrorMessage(errorMessage);
        deferredResult.setResult((R) ResponseDTO.success(headerDTO, null));
    }
}
